export const imageUtil = {
  getSize: (file) => {
    return new Promise(resolve => {
      let img = new Image()
      img.src = file

      img.onabort = () => {
        resolve(null)
      }
      img.onload = () => {
        resolve({
          width: img.width,
          height: img.height
        })
      }
    })
  },
  croppedToBase64: function (data) {

    return new Promise((resolve, reject) => {
      const src = data.src;
      const x = data.x
      const y = data.y
      const width = data.width
      const height = data.height
      let tmp = document.createElement('canvas');
      let context = tmp.getContext('2d');
      tmp.width = width
      tmp.height = height
      const img = new Image();
      img.src = src
      img.onload = function () {
        context.drawImage(img, x, y, width, height,0,0,width, height)
        let imageData = tmp.toDataURL('image/jpeg', 1.0);
        resolve(imageData)
      };
      img.onabort = function () {
        reject("失败")
      };

    })

  },
  //1,先将base64转换为blob
  dataURLtoBlob(dataurl) {
    var arr = dataurl.split(','),
      mime = arr[0].match(/:(.*?);/)[1],
      bstr = atob(arr[1]),
      n = bstr.length,
      u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
  },
  //2,再将blob转换为file
  blobToFile(theBlob, fileName){
    theBlob.lastModifiedDate = new Date();  // 文件最后的修改日期
    theBlob.name = fileName;                // 文件名
    return new File([theBlob], fileName, {type: theBlob.type, lastModified: Date.now()});
  },
  fileToUrl(blob) {
    return URL.createObjectURL(blob)
  }

}